package lib.wzh.com.libcore.framework.exception;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import lib.wzh.com.libcore.framework.enums.ResponseEnum;
import lib.wzh.com.libcore.framework.response.BaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;

/**
 * @Author lib
 * @Date 2021/11/23 16:01
 * @ClassName GlobalException
 * @Version v1.0
 */

@RestControllerAdvice
public class GlobalHandlerException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<Map<String, String>> methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult result = e.getBindingResult();
        Map<Object, Object> resultMap = CollUtil.newHashMap();
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(fieldError -> resultMap.put(fieldError.getField(),fieldError.getDefaultMessage()));
        }
        return new BaseResponse<>(ResponseEnum.VALIDATED_ERROR.code(), JSONUtil.toJsonStr(resultMap), ResponseEnum.VALIDATED_ERROR.success(),null);
    }

    @ExceptionHandler(BusinessException.class)
    public <T> BaseResponse<T> businessException(BusinessException e){
        String code = StringUtils.isBlank(e.getCode())? ResponseEnum.FAIL.code() : e.getCode();
        return new BaseResponse<>(code,e.getMessage(),false,null);
    }

    @ExceptionHandler(Exception.class)
    public <T> BaseResponse<T> exception(Exception e){
        return new BaseResponse<>(ResponseEnum.FAIL.code(), e.getMessage(),false,null);
    }

}
